package com.dude.screens;

import com.dude.R;
import com.dude.utils.OnFirstRun;
import com.dude.utils.TTS;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;

public class MainScreen extends Activity implements TextToSpeech.OnInitListener
{
    // its just a checksum.
    private static final int MY_DATA_CHECK_CODE = 1234;
    
    //shared preference name
    private static final String firstRunString = "FIRSTRUN";
    
	private Button findIt;
	private Button profilesManager;
	private MenuItem settingsMenu;
	private MenuItem helpMenu;
	private TextToSpeech tts;
	private boolean useVoice; 
	private boolean firstRun = false;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        
        // set the layout of this screen as defined in the 'main' layout xml
        setContentView(R.layout.main);
        
        // allocate the buttons using predefined layout
        findIt = (Button) findViewById(R.id.find_it);
        profilesManager = (Button) findViewById(R.id.profiles_manager);
        
        SharedPreferences settings = getSharedPreferences(Settings.settings, 0);
        useVoice = settings.getBoolean(Settings.useVoicePref, false);
        
        if (useVoice && tts == null )
        {
			// Fire off an intent to check if a TTS engine is installed
	        Intent checkIntent = new Intent();
	        checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
	        startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
        }
        
        // make each button to open the corresponding screen        
        findIt.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View target) {
				startActivity(new Intent(MainScreen.this, FindObjectScreen.class));
			}
		});
        
        profilesManager.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View target) {
				startActivity(new Intent(MainScreen.this, ProfilesManager.class));
			}
		});
        
        
        
        findIt.setOnLongClickListener(new OnLongClickListener(){

			@Override
			public boolean onLongClick(View v) {
				if (tts != null)
					tts.speak(findIt.getText().toString(), TextToSpeech.QUEUE_FLUSH,null);
				
				return true;
			}
        	
        });
        
        profilesManager.setOnLongClickListener(new OnLongClickListener(){

			@Override
			public boolean onLongClick(View v) {
				if (tts != null)
					tts.speak(profilesManager.getText().toString(), TextToSpeech.QUEUE_FLUSH,null);
				
				return true;
			}			 
		 });
        
        // if this is the first time the application is run do the following
        firstRun = settings.getBoolean(firstRunString, true);
        if (firstRun)
        {
        	SharedPreferences.Editor editor = settings.edit();
        	editor.putBoolean(firstRunString, false);
        	editor.commit();      	
        	OnFirstRun ofr = new OnFirstRun(MainScreen.this);
        	ofr.initialize();   
        }
        
    }
    
    
    // when user clicks the menu button he can go to settings or help screens
 	@Override
 	public boolean onCreateOptionsMenu(Menu menu) {
 		settingsMenu = menu.add("settings");
 		helpMenu = menu.add("help");
 		return true;
 	}

 	// change the current view mode (probably unnecessary)
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	if (item == settingsMenu)
    		startActivity(new Intent(MainScreen.this, Settings.class));
    	else if (item == helpMenu)
    		startActivity(new Intent(MainScreen.this, HelpScreen.class));
    	
    	return true;
    }


	@Override
	public void onInit(int status) {	
        tts.speak("Hi, welcome to FindIt, please press a long click on a button to hear it's action.",
        		TextToSpeech.QUEUE_FLUSH,  // Drop all pending entries in the playback queue.
        		null);
	}
	
    /**
     * This is the callback from the TTS engine check, if a TTS is installed we
     * create a new TTS instance (which in turn calls onInit), if not then we will
     * create an intent to go off and install a TTS engine
     * @param requestCode int Request code returned from the check for TTS engine.
     * @param resultCode int Result code returned from the check for TTS engine.
     * @param data Intent Intent returned from the TTS check.
     */
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (requestCode == MY_DATA_CHECK_CODE)
        {
            if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS)
            {
                // success, create the TTS instance
                tts = TTS.getInstance(this, this);
            }
            else
            {
                // missing data, install it
                Intent installIntent = new Intent();
                installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                startActivity(installIntent);
            }
        }
    }
    
    public void onResume()
    {
    	super.onResume();
    	
    	SharedPreferences settings = getSharedPreferences(Settings.settings, 0);
        useVoice = settings.getBoolean(Settings.useVoicePref, false);
         
        if (useVoice && tts == null)
        {
        	// Fire off an intent to check if a TTS engine is installed
 	       	Intent checkIntent = new Intent();
 	       	checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
 	       	startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
        }
    }
    
    /**
     * Be kind, once you've finished with the TTS engine, shut it down so other
     * applications can use it without us interfering with it :)
     */
    @Override
    public void onDestroy()
    {
        TTS.dispose(); //clean text to speech
        
        FindObjectScreen.cleanBitmapsFromMemory(); // clean bitmaps from memory
        
        super.onDestroy();
    }
    
}